package com.mucd.blogblogs7000.service;

import com.mucd.blog.entity.ColumnEntity;
import com.mucd.blog.result.R;
import com.mucd.blog.statuscode.MyException;
import com.mucd.blog.statuscode.StatusCode;
import com.mucd.blogblogs7000.dao.ColumnDao;
import lombok.extern.log4j.Log4j2;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @Author mucd
 */
@Service
@Log4j2
public class ColumnService {

    @Resource
    private ColumnDao columnDao;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CacheManager cacheManager;

    /**
     * 3000秒后更新redis中的内容
     */
    @Cacheable(value = "columnList")
    public List<ColumnEntity> saveColumn() {
        List<ColumnEntity> columnEntities = columnDao.selectList(null);
        //将这些栏目存到redis中
        ListOperations<String, Object> opsList = redisTemplate.opsForList();
        Long column = opsList.leftPushAll("columnList", columnEntities);
        log.info("更新column内容:{}", column);
        return columnEntities;
    }

    /**
     * 获取所有栏目
     * 会从redis中读取出来,不会从数据库中读取
     *
     * @return R
     */

    public R list() {
        //从redis中读取出来
        //将这些栏目存到redis中
        ListOperations<String, Object> opsList = redisTemplate.opsForList();
        List<Object> columnList = opsList.range("columnList", 0, -1);
        log.info("取出来的数据{}", columnList);

        return R.ok(columnList);
    }

    /**
     * 新增栏目
     *
     * @param columnEntity
     * @return
     */
    @CacheEvict(value = "columnList", allEntries = true)//清除缓存中的数据
    public R save(ColumnEntity columnEntity) {
        int insert = columnDao.insert(columnEntity);
        if (insert <= 0) {
            return R.error("新增栏目失败");
        }

        return R.ok("操作成功");
    }

    /**
     * 删除栏目
     *
     * @param columnId
     * @return
     */
    @CacheEvict(value = "columnList", allEntries = true)//清除缓存中的数据
    public R delete(List<Integer> columnId) {
        int i = columnDao.deleteBatchIds(columnId);
        if (i <= 0) {
            return R.error("删除栏目失败");
        }
        return R.ok("操作成功");
    }

    /**
     * 修改栏目
     *
     * @param columnEntity
     * @return
     */
    @CacheEvict(value = "columnList", allEntries = true)//清除缓存中的数据
    public R updateById(ColumnEntity columnEntity) {
        int i = columnDao.updateById(columnEntity);
        if (i <= 0) {
            return R.error("修改栏目失败");
        }
        return R.ok("操作成功");
    }
}
